import pyautogui
import time
import pyperclip
from datetime import datetime
from commons_util import Util
import os
import pickle


class DailyQues:

    def __init__(self):
        # 加载已有问题
        self.answers = []
        i = 0
        for line in open('./question.txt', 'r', encoding='utf-8'):
            key = line.split("##")[0]
            value = line.split("##")[1]
            self.answers.append(
                {'key': key, 'value': value}
            )
        # self.qh = None
        # if os.path.exists('./question-hash.pkl'):
        #     self.qh = pickle.load(open('./question-hash.pkl', 'r'))
        # else:
        #     self.qh = {}

    def reload_hash_file(self):
        pickle.dump(self.qh, open('./question-hash.pkl', 'w'))


    def get_answer(self, text):
        res = ""
        best_ratio = -1
        for ans in self.answers:
            cur_ratio = Util.string_similar(text, ans["key"])
            if cur_ratio > best_ratio:
                best_ratio = cur_ratio
                res = ans["value"]
        # print("对应答案：" + res)
        # print("对应准确度，" + str(best_ratio))
        return res, best_ratio

    def click_and_enter(self, res):
        pyautogui.doubleClick(400, 2230)
        pyperclip.copy(res)
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.hotkey('enter')
        # time.sleep(0.1)
        # pyautogui.doubleClick(387, 1538)
        # pyautogui.hotkey('ctrl', 'v')
        # pyautogui.hotkey('enter')


    def doit(self):
        # Util.click(660, 1666)
        img = Util.get_screenshot(region=[166, 1626, 430, 60], sub_folder='question')
        text = Util.get_text_from_img(img)
        res, ratio = self.get_answer(text)
        if ratio <= 0.3:
            # print(path)
            print(text)
            # print(res)
            print(ratio)
            print('----------------')
        else:
            self.click_and_enter(res)
            print(text)
            print(res)
            print(ratio)
            print("success hit")
            print(time.strftime("%m-%d-%H-%M-%S", time.localtime()))
        sub_folder = "/question"
        path = f'./images{sub_folder}/img_{time.strftime("%m-%d-%H-%M-%S", time.localtime())}.jpg'
        img.save(path)


    def loop(self):
        while True:
            ct = time.time()
            t = time.strftime("%M-%S", time.localtime(ct))
            mi = int(t.split("-")[0])
            se = int(t.split("-")[1])
            ms = (ct - int(ct)) * 1000
            if mi in (0, 15, 30, 45) and se >= 15 and ms >= 300:
                # print(t)
                # now = datetime.now()
                self.doit()
                # print(f'cost : {(datetime.now() - now)}')
                time.sleep(70)

    def test(self):
        root = r'./images/question'
        now = datetime.now()
        if os.path.exists(root):
            files = os.listdir(root)
            low_ratio = 210
            for file in files:
                img_path = root + '/' + file
                text = Util.get_text_from_img(img_path)
                res, ratio = self.get_answer(text)
                # self.click_and_enter(res)
                print(img_path)
                print(text)
                print(res)
                low_ratio = min(low_ratio, ratio)
                print('----------------')
            avg = (datetime.now() - now).seconds / len(files)
        print(f'average time: {avg}')
        # print(f'lowest ratio is {low_ratio}')


import win32api
import ctypes


def move(x, y):
    ctypes.windll.user32.SetCursorPos(x, y)


def press(x, y, button=1):
    buttionAction = 2 ** ((2 * button) - 1)
    win32api.mouse_event(buttionAction, x, y)


def release(x, y, button=1):
    buttionAction = 2 ** (2 * button)
    win32api.mouse_event(buttionAction, x, y)


if __name__ == "__main__":
    dq = DailyQues()
    dq.test()

    # pyautogui.click(189, 1418, clicks=3, interval=1, duration=2)
